﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Consul;
using DnsClient;
using IdentityServer4.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Resilience;
using User.Identity.Authentication;
using User.Identity.Infrastructure;
using User.Identity.Models;
using User.Identity.Services;

namespace User.Identity
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
                .AddExtensionGrantValidator<SmsAuthCodeValidator>()
                .AddDeveloperSigningCredential()
                .AddInMemoryClients(Config.GetClients())
                .AddInMemoryIdentityResources(Config.GetIdentityResources())
                .AddInMemoryApiResources(Config.GetApiResources());
            services.AddOptions();
            services.Configure<ServiceDiscoveryOptions>(Configuration.GetSection("ServiceDiscovery"));
            services.AddSingleton<IDnsQuery>(p =>
            {
                return new LookupClient(IPAddress.Parse("127.0.0.1"), 8600);
            });
            services.AddSingleton<ResilienceHttpClientFactory>(sp =>
            {
                var logger = sp.GetRequiredService<ILogger<ResilienceHttpClient>>();
                var httpContextAccessor = sp.GetRequiredService<IHttpContextAccessor>();
                return new ResilienceHttpClientFactory(logger, httpContextAccessor, 5, 5);
            });
            services.AddSingleton<IHttpClient>(sp =>
            {
                return sp.GetRequiredService<ResilienceHttpClientFactory>().GetResilienceHttpClient(); 
            });
            services.AddTransient<IProfileService, ProfileService>();
            services.AddScoped<IAuthCodeService, SmsAuthCodeService>();
            services.AddScoped<IUserService, UserService>();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            lifetime.ApplicationStarted.Register(OnStart);
            lifetime.ApplicationStopped.Register(OnStop);
            app.UseIdentityServer();
            app.UseMvc();
        }

        private void OnStop()
        {
            var client = new ConsulClient();
            client.Agent.ServiceDeregister("user_identity_127.0.0.1:8003").ConfigureAwait(false);
        }

        private void OnStart()
        {

            var client = new ConsulClient();
            var agentServiceRegistration = new AgentServiceRegistration()
            {
                ID = "user_identity_127.0.0.1:8003",
                Address = "127.0.0.1",
                Name = "user_identity",
                Port = 8003,
                Check = new AgentServiceCheck()
                {
                    HTTP = "http://127.0.0.1:8003/api/HealthCheck/Ping",
                    Interval = TimeSpan.FromSeconds(30),
                    DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1)
                }
            };

            client.Agent.ServiceRegister(agentServiceRegistration).ConfigureAwait(false);
        }
    }
}
